//
//  WBOAuthViewController.swift
//  仿写微博
//
//  Created by tuimao on 17/7/18.
//  Copyright © 2017年 tuimao. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD
class WBOAuthViewController: UIViewController {
    fileprivate lazy var wbView = WKWebView()
    
    //记载webView
    override func loadView() {
        view = wbView
        //背景色
        view.backgroundColor = UIColor.white
        //取消滚动
        wbView.scrollView.isScrollEnabled = false
        // 设置导航栏
        title = "登录新浪微博"
        // 导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isback: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .plain, target: self, action: #selector(autoFill))
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载授权页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        
        // 1> URL 确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        
        // 2> 建立请求
        let request = URLRequest(url: url)
        
        // 3> 加载请求
        wbView.load(request)
        //代理
        wbView.navigationDelegate = self
    }
    //MARK:监听方法
    @objc fileprivate func close(){
        dismiss(animated: true, completion: nil)
    }
    /// 自动填充 - WebView 的注入，直接通过 js 修改 `本地浏览器中` 缓存的页面内容
    /// 点击登录按钮，执行 submit() 将本地数据提交给服务器！
    @objc private func autoFill() {
        // 准备 js
        let js = "document.getElementById('userId').value = '18651893175'; " +
        "document.getElementById('passwd').value = 'liweihuiyunying';"
        
        // 让 webview 执行 js
        wbView.evaluateJavaScript(js, completionHandler: nil)
    }
}

extension WBOAuthViewController : WKNavigationDelegate{
    //MARK:  拦截URL
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void){
        //判断空值
        guard let url = navigationAction.request.url,
            let successCode = url.query?.hasPrefix("code="),
            let code = url.query?.substring(from: "code=".endIndex)
            else {
            //允许跳转
            decisionHandler(.allow)
            return
        }
        //当跳转链接中包含登录或者取消微博的时候（包含http:baidu）
        if url.absoluteString.hasPrefix(WBRedirectURI){
            //当点击登录的时候
            if successCode{
                print("code--\(code)")
                //获取token的请求的回调
                WBNetworkManager.shared.loadAccessToken(code: code, completion: { (issuccess) in
                    if issuccess {
                        //成功向BossVC发送通知
                        NotificationCenter.default.post(
                            name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification),
                            object: nil)
                        //不允许跳转
                        decisionHandler(.cancel)
                        self.close()
                    }else{
                        SVProgressHUD.showError(withStatus: "登录失败")
                        SVProgressHUD.dismiss()
                        //不允许跳转
                        decisionHandler(.cancel)
                    }
                })
            }
        }
        //允许跳转
        decisionHandler(.allow)
    }
    //MARK: 开始的的提示
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        SVProgressHUD.show()
    }
     //MARK: 开始的的提示
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
}



